#!/usr/bin/env python

"""
This script changes the directory path for a release once it goes EOL.

In principle it should be run about a week after the said release went EOL.
"""

from __future__ import print_function
import sys
import re
import os

sys.path.insert(0, os.path.join(os.path.dirname(
    os.path.abspath(__file__)), '..'))
import mirrormanager2.lib
from optparse import OptionParser

archiveCategory = 'Fedora Archive'
originalCategory = 'Fedora Linux'


def doit(session, original_cat, archive_cat, directory_re):
    c = mirrormanager2.lib.get_category_by_name(session, original_cat)
    if c is None:
        raise Exception(
            "No category could be found by the name: %s" % original_cat)
    a = mirrormanager2.lib.get_category_by_name(session, archive_cat)
    if a is None:
        raise Exception(
            "No category could be found by the name: %s" % archive_cat)
    originaltopdir = c.topdir.name
    archivetopdir = os.path.join(a.topdir.name, 'fedora', 'linux')
    dirRe = re.compile(directory_re)
    for d in c.directories:
        if dirRe.search(d.name):
            for r in d.repositories:
                t = os.path.join(archivetopdir, d.name[len(originaltopdir)+1:])
                print("trying to find %s" % t)
                new_d = mirrormanager2.lib.get_directory_by_name(session, t)
                if new_d is None:
                    raise Exception(
                        "Unable to find a directory in [%s] for %s" % (
                            archive_cat, d.name))
                r.directory = new_d
                r.category = a
                session.add(r)
                session.commit()
                print("%s => %s" % (d.name, t))


def main():
    parser = OptionParser(usage=sys.argv[0] + " [options]")
    parser.add_option(
        "-c", "--config", dest="config",
        default='/etc/mirrormanager/mirrormanager2.cfg',
        help="Configuration file to use (defaults to "
        "/etc/mirrormanager/mirrormanager2.cfg)")
    parser.add_option(
        "--originalCategory", metavar="CATEGORY", dest="originalCategory",
        type="string", help="original Category (default=%s)" %
            originalCategory, default=originalCategory)
    parser.add_option(
        "--archiveCategory", metavar="CATEGORY", dest="archiveCategory",
        type="string", help="archive Category (default=%s)" %
            archiveCategory, default=archiveCategory)
    parser.add_option(
        "--directoryRe", metavar="RE", dest="directoryRe",
        type="string", default=None,
        help="subdirectory regular expression to move (e.g. '/7/') "
        "[required]")

    (options, args) = parser.parse_args()
    if options.directoryRe is None:
        parser.print_help()
        sys.exit(1)

    d = dict()
    with open(options.config) as config_file:
        exec(compile(config_file.read(), options.config, 'exec'), d)

    session = mirrormanager2.lib.create_session(d['DB_URL'])

    try:
        doit(
            session,
            options.originalCategory,
            options.archiveCategory,
            options.directoryRe)
        return 0
    except Exception as err:
        print(err)
        return 1


if __name__ == "__main__":
    sys.exit(main())
